﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebAPI.CustomFilter
{
    /// <summary>
    /// 限流过滤器
    /// </summary>
    public class RateLimitFilter : IAsyncActionFilter
    {
        private readonly IMemoryCache memCache;

        public RateLimitFilter(IMemoryCache memCache)
        {
            this.memCache = memCache;
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            //Console.WriteLine("RateLimitActionFilter 执行action前");
            string ip = context.HttpContext.Connection.RemoteIpAddress.ToString();
            string cacheKey = $"lastvisittick_{ip}";
            long? lastVisit = memCache.Get<long?>(cacheKey);
            if (lastVisit == null || Environment.TickCount64 - lastVisit > 200) // Environment.TickCount64 系统时间
            {
                memCache.Set(cacheKey, Environment.TickCount64, TimeSpan.FromSeconds(10));//避免长期不访问的用户，占据缓存的内存
                await next();
                //Console.WriteLine("RateLimitActionFilter 执行action后");
            }
            else
            {
                JsonResult result = new JsonResult(new
                {
                    Code = 429,
                    Msg = "您的,手速太快,访问太频繁了！"
                 });
                context.Result = result;
            }
        }
    }


    [AttributeUsage(AttributeTargets.Method)]
    public class RateLimitAttribute : Attribute { }
}
